<template>
  <div
      class="new-turnover route-page"
      :class="$store.getters.isMobile ? 'back-class' : ''"
  >
    <section class="header">
      <a-page-header
          :class="isDrawer || microAppData.isMainDrawer ? 'hide-back' : ''"
          @back="goBack">
        <template #title>
          <span class="title">新建收支流水</span>
          <span class="subtitle" v-if="subtitle.length>0">{{ subtitle }}</span>
        </template>
      </a-page-header>
    </section>
    <section class="content">
      <a-alert type="info" v-if="!processApprove" style="margin-bottom: 10px">
        <template #message>
          收支流水暂未开启审批，点击”
          <span v-if="Approveis_admin" class="link" @click.stop="goSetting"
          >配置</span
          >
          <span v-else class="link" style="cursor: not-allowed">配置</span>
          “可快速设置。
        </template>
      </a-alert>
      <a-form layout="vertical">
        <a-card title="流水信息">
          <a-card-grid class="w-100p">
            <a-row :gutter="[12, 12]" :wrap="true">
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="借贷标" v-bind="validateInfos.loan_type">
                  <a-select
                      v-model:value="formData.loan_type"
                      placeholder="请选择"
                      :options="list.loanTypeList"
                      :disabled="loanTypeDisabled"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="币种" v-bind="validateInfos.currency">
                  <a-select
                      v-model:value="formData.currency"
                      placeholder="请选择"
                      :options="list.currencyList"
                      disabled
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="发生额" v-bind="validateInfos.amount">
                  <a-input-number
                      class="w-100p"
                      placeholder="请输入"
                      v-model:value="formData.amount"
                      :min="0"
                      @change="handleAmountChange"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item
                    label="入账日期"
                    v-bind="validateInfos.income_date"
                >
                  <a-date-picker
                      class="w-100p"
                      v-model:value="formData.income_date"
                      :valueFormat="dateFormatStr"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="流水账户" v-bind="validateInfos.account_id"
                             style="position: relative">
                  <!--                  <a-select-->
                  <!--                      v-model:value="formData.account_id"-->
                  <!--                      placeholder="请选择"-->
                  <!--                      :options="list.accountList"-->
                  <!--                  />-->
                  <a-cascader style="width: 100%" placeholder="选择流水账户"
                              v-model:value="formData.account_id" :options="companyList"
                              :load-data="getAccount"/>

                  <a-button type="link" class="fast-add"
                            @click="addAccount">快速添加
                  </a-button>
                </a-form-item>


              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="匹配日期" v-bind="validateInfos.match_date">
                  <a-date-picker
                      class="w-100p"
                      v-model:value="formData.match_date"
                      :valueFormat="dateFormatStr"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="凭证号" v-bind="validateInfos.voucher_no">
                  <a-input
                      class="w-100p"
                      placeholder="请输入"
                      v-model:value="formData.voucher_no"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card-grid>
          <a-card-grid class="w-100p">
            <a-row :gutter="[12, 12]" :wrap="true">
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item
                    label="对方单位名称"
                    v-bind="validateInfos.owner_id"
                >
                  <TenantComponent
                    :ownerId="formData.owner_id"
                    titleser="选择对方单位"
                    :types="isdisabled"
                    @selectcancel="handleCompanyChange"
                    @request="$utils.commonRequest"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item
                    label="付款公司"
                    v-bind="validateInfos.invoice_title_id"
                >
                  <a-select
                      v-model:value="formData.invoice_title_id"
                      placeholder="请选择付款公司"
                      :options="invoiceList"
                      :disabled="!formData.owner_id"
                  >
                    <template #dropdownRender="{ menuNode: menu }">
                      <v-nodes :vnodes="menu"/>
                      <a-divider style="margin: 4px 0"/>
                      <div
                          class="text-center"
                          @mousedown="(e) => e.preventDefault()"
                          @click="addInvoice"
                      >
                        <a-button type="link">
                          <template #icon>
                            <PlusOutlined/>
                          </template>
                          新增
                        </a-button>
                      </div>
                    </template>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="联系人" v-bind="validateInfos.link_name">
                  <a-input
                      class="w-100p"
                      placeholder="请输入"
                      v-model:value="formData.link_name"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="汇款方式" v-bind="validateInfos.remit_type">
                  <a-select
                      v-model:value="formData.remit_type"
                      placeholder="请选择"
                      :options="list.remitTypeList"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item
                    label="开户银行"
                    v-bind="validateInfos.stream_account"
                >
                  <a-input
                      class="w-100p"
                      placeholder="请输入"
                      v-model:value="formData.stream_account"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item
                    label="对方账户"
                    v-bind="validateInfos.other_account"
                >
                  <a-input
                      class="w-100p"
                      placeholder="请输入"
                      v-model:value="formData.other_account"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="摘要" v-bind="validateInfos.abstract">
                  <a-textarea
                      placeholder="请输入"
                      :auto-size="{ minRows: 3 }"
                      v-model:value="formData.abstract"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="$store.getters.isMobile ? 24 : isDrawer ? 6 : 4">
                <a-form-item label="备注" v-bind="validateInfos.remark">
                  <a-textarea
                      placeholder="请输入"
                      :auto-size="{ minRows: 3 }"
                      v-model:value="formData.remark"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card-grid>
        </a-card>
      </a-form>
      <section class="mt-10">
        <attachment-info
            :params="attachParams"
            typeFrom="bill"
            @getObjectId="getObjectId"
        />
      </section>
    </section>
    <section class="footer">
      <a-space>
        <a-button @click="cancel">取消</a-button>
        <a-button
            v-if="processApprove"
            type="primary"
            @click="submit"
            :loading="loading"
        >
          保存&发起审批
        </a-button>
        <a-button
            v-else
            type="primary"
            @click="submit"
            :loading="loading"
        >
          {{ billId ? "保存&生效" : "保存" }}
        </a-button>
      </a-space>
    </section>

    <!-- 新增发票抬头 -->
    <AddInvoice
        :visible="invoiceVisible"
        :ownerId="formData.owner_id"
        @successChange="successChange"
        @closeChange="invoiceVisible = false"
    />

    <account-add
        @cancel="addAccountClose"
        @success="addSuccess"
        :visible="addVisible"
        @request="$utils.commonRequest"
    ></account-add>
  </div>
</template>

<script>
import {
  computed,
  createVNode,
  defineComponent,
  onBeforeUnmount,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import {useRouter, useRoute} from "vue-router";
import AttachmentInfo from "../../../components/contract/AttachmentInfo/index.vue";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons-vue";
import {Form, message, Modal} from "ant-design-vue";
import store from "../../../store";
import request from "../../../common/utils/request";
import moment from "moment";

const useForm = Form.useForm;
const dateFormatStr = "YYYY-MM-DD";
import _ from "lodash";

import AddInvoice from "@/views/village/OwnerManage/modules/AddInvoice.vue";
import AccountAdd from '@/views/setting/UserAccount/modules/AccountAdd.vue';
import { TenantComponent } from "bl-common-vue3";

export default defineComponent({
  name: "newTurnover",
  components: {
    AccountAdd,
    AttachmentInfo,
    PlusOutlined,
    AddInvoice,
    TenantComponent,
    VNodes: (_, {attrs}) => {
      return attrs.vnodes;
    },
  },
  props: {
    turnoverDetail: {
      type: Object,
      default: () => ({}),
    },
    isDrawer: {
      type: Boolean,
      default: false,
    },
    ownerIdByDrawer: {
      type: [Number, String],
      default: 0,
    },
    bindExtraInfo: {
      type: Object,
      default: () => ({}), // 专项预存 (如水电充值等)
    },
    queryBillId: {
      type: [Number, String],
      default: 0,
    },
    queryType: {
      type: String,
      default: "",
    },
    defaultLoanType: {
      type: String,
      default: '',
    },
    defaultAmount: {
      type: Number,
      default: 0,
    }
  },
  setup(props, context) {
    const $router = useRouter();
    const $route = useRoute();
    const goBack = () => {
      $router.back();
    };
    const isdisabled = ref(false);
    const today = moment();

    const microAppData = window?.microApp?.getData()

    let bindExtraInfo = {};

    watch(
        () => props.bindExtraInfo,
        (val) => {
          if (val) {
            bindExtraInfo = val
          }
        },
        {immediate: true}
    );
    if (microAppData.record) {
      bindExtraInfo = microAppData.record
    }

    const isDrawer = computed(()=>{
      if(microAppData?.record?.isDrawer){
        return microAppData?.record?.isDrawer
      }else{
        return props.isDrawer
      }
    })

    const isDisSpecial = computed(() => _.isEmpty(bindExtraInfo));

    const state = reactive({
      loanTypeDisabled: false,
      billId: 0,
      maxAmount: -1,
      attachParams: {
        type: 2,
      },
      isDisabledSingleType: false,

      // 是否有审批
      processApprove: true,
      Approveis_admin: false,
      Approve_id: 0,

      invoiceList: [], //发票抬头列表
      invoiceVisible: false,
      subtitle: "",
      addVisible: false,
      companyList: [],

    });


    const formData = ref({
      // 借贷类型
      loan_type: undefined,
      // 发生额
      amount: "",
      // 入账日期
      income_date: today,
      // 对方单位名称
      owner_id: undefined,
      company_name: "",
      // 付款公司
      invoice_title_id: undefined,
      // 流水账户
      account_id: undefined,
      //  开户银行
      stream_account: "",
      // 	匹配日期
      match_date: today,
      // 	联系人
      link_name: "",
      // 汇款方式
      remit_type: undefined,
      // 对方账号
      other_account: "",
      // 	凭证号
      voucher_no: "",
      // 收据编号
      // receipt_no: "",
      // 摘要
      abstract: "",
      // 币种
      currency: "CNY",
      // 备注
      remark: "",
      // 专项
      single_type: "",
    });
    const ruleRef = ref({
      loan_type: [{required: true, message: "必选"}],
      amount: [{required: true, message: "必填"}],
      income_date: [{required: true, message: "必选"}],
      owner_id: [{required: true, message: "必填"}],
      account_id: [{required: true, message: "必选"}]
    });

    const {resetFields, validate, validateInfos} = useForm(formData, ruleRef);

    const handleCompanyChange = (id , data) => {
      formData.value.other_account = data?.invoice_info?.account;
      formData.value.stream_account = data?.invoice_info?.bank;
      formData.value.company_name = data.name;
      formData.value.owner_id = id;
      formData.value.invoice_title_id = undefined;
      getInvoiceData(id);
    };

    const handleAmountChange = (value) => {
      if (state.billId && value > state.maxAmount) {
        message.warning("收支流水发生额不能大于账单需收！");
        formData.value.amount = state.maxAmount;
      }
    };

    watch(
        () => props.ownerIdByDrawer,
        (val) => {
          if (val) {
            formData.value.owner_id = Number(props.ownerIdByDrawer);
          }
        },
        {immediate: true}
    );

    const getBuildBindByDetail = () => {
      const {turnoverDetail} = props;
      return {
        village: {
          id: turnoverDetail.village_id,
          name: turnoverDetail.village_name,
        },
        build: [
          {
            id: turnoverDetail.build_id,
            build_name: turnoverDetail.build_name,
          },
        ],
        room: [
          {
            ...turnoverDetail,
            extra: {
              layer_id: turnoverDetail.layer_id,
              layer_name: turnoverDetail.layer_name,
              build_id: turnoverDetail.build_id,
              build_name: turnoverDetail.build_name,
              village_id: turnoverDetail.village_id,
              village_name: turnoverDetail.village_name,
            },
          },
        ],
      };
    };

    const loading = ref(false);
    const submit = () => {
      validate()
          .then(() => {
            loading.value = true;
            let params = JSON.parse(JSON.stringify(formData.value));
            params.needMsg = true;
            params.object_id = state.attachParams.object_id;
            if (state.billId) {
              params.bill_id = state.billId;
            }
            params.company_id = formData.value.owner_id;
            params.income_date = moment(formData.value.income_date).format(
                dateFormatStr
            );
            params.match_date = moment(formData.value.match_date).format(
                dateFormatStr
            );
            if (Object.keys(props.turnoverDetail).length) {
              // 租客流水新增收支流水
              const build_bind = getBuildBindByDetail();
              params.build_bind = build_bind;
            }
            if (state.isDisabledSingleType) {
              params.extra = {
                cost_type: bindExtraInfo.cost_type,
                energy_id: bindExtraInfo?.id || 0,
                payment_type: bindExtraInfo?.payment_type || 0,
              };
            }

            if (formData.value.account_id) {
              params.org_branch_id = formData.value.account_id[0];
              params.account_id = formData.value.account_id[1];
            }
            params.approval = state.processApprove;

            let requestUrl = "/bill/createStream";
            let queryType = props.queryType || $route.query.type;
            if (queryType == "latefee") {
              requestUrl = "/bill/LateSettle";
            }
            request.post("/org", requestUrl, params).then((res) => {
              message.success(res.msg || "保存成功!");
              if (props.isDrawer || window?.microApp?.getData()?.isMainDrawer) {
                if (window?.microApp?.getData()?.isMainDrawer) {
                  window?.microApp?.getData()?.closeDrawer();
                } else {
                  context.emit("save");
                }
              } else {
                goBack();
              }
            });
          })
          .finally(() => {
            loading.value = false;
          });
    };

    const cancel = () => {
      if (props.isDrawer || window?.microApp?.getData()?.isMainDrawer) {
          if (window?.microApp?.getData()?.isMainDrawer) {
              window?.microApp?.getData()?.closeDrawer();
          } else {
              context.emit("cancel");
          }
       } else {
            goBack();
       }
    };

    const list = reactive({
      currencyList: [],
      loanTypeList: [],
      accountList: [],
      remitTypeList: [],
      specialProjects: [
        {
          value: "",
          label: "非专项",
        },
      ],
    });

    const getSetting = () => {
      // 获取配置
      request
          .get("/org", "/approval/publish/process", {
            alias: formData.value.loan_type == 'INCOME' ? "bill_stream_add" : 'pay_bill_stream_add',
          })
          .then((res) => {
            state.processApprove = res.info.process; //判断是否开启
            state.Approveis_admin = res.info.is_admin; //判断是否有权限
            state.Approve_id = res.info.id;
          });
    };

    watch(
      () => formData.value.loan_type,
      () => {
        getSetting();
      }
    );

    const goSetting = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: state.Approve_id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };


    const getObjectId = (id) => {
      state.attachParams.object_id = id;
    };

    // 获取对应租客的开票信息
    const getInvoiceData = (owner_id) => {
      request
          .get("/org", "/org/owner/invoice/title/all", {owner_id})
          .then((res) => {
            state.invoiceList = res.list.map((item) => {
              return {
                label: item.title,
                value: item.id,
              };
            });
          });
    };

    const addInvoice = () => {
      state.invoiceVisible = true;
    };

    const successChange = () => {
      state.invoiceVisible = false;
      getInvoiceData(formData.value.owner_id);
    };

    const getCompanyList = () => {
      request.get("/org", "/company/orgAndBranch").then(res => {
        console.log(res)
        state.companyList = res.list.map(item => {
          return {
            label: item.company,
            value: item.id,
            isLeaf: false
          }
        })
        if (state.companyList.length == 1) {
          getAccount([state.companyList[0]])
        }
      })
    }

    const getAccount = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      let params = {
        page: 1,
        pageSize: 9999,
        org_branch_id: targetOption.value,
      };
      if (state.billId) {
        params.billId = state.billId;
      }
      request
          .get("/org", "/manage/account", params)
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                label: item.name,
                value: item.id,
                isLeaf: true,
              }));
              state.companyList = [...state.companyList];
              if (state.companyList.length == 1 && targetOption.children.length == 1) {
                  formData.value.account_id = [state.companyList[0].value,targetOption.children[0].value]
              }
            }
          });
    };


    const init = () => {
      store.dispatch("BillInit").then((data) => {
        if (bindExtraInfo?.cost_type_txt) {
          state.subtitle = '#' + bindExtraInfo?.cost_type_txt;
        }

        list.currencyList = data.currency;
        list.loanTypeList = data.loan_type;
        list.remitTypeList = data.remit_money;
        list.specialProjects = [list.specialProjects[0], ...data.stream_config];
        let buildIds = "";
        let incomelate = "";
        let queryBillID = props.queryBillId || $route.query.billId;
        if (queryBillID) {
          const billDetail = store.getters.billMatchAccountDetail;
          // console.log("billDetail", billDetail);
          if (
              billDetail &&
              billDetail.bill_id &&
              billDetail.bill_id == queryBillID
          ) {
            state.billId = billDetail.bill_id;
            state.maxAmount = Number(billDetail.amount);
            formData.value.loan_type = billDetail.loan_type;
            formData.value.owner_id = billDetail.owner_id;
            state.loanTypeDisabled = true;
            buildIds = billDetail.buildIds;
            let queryType = props.queryType || $route.query.type;
            if (queryType == "latefee") {
              formData.value.amount = billDetail.latefeeAmount;
            } else {
              formData.value.amount = billDetail.amount;
            }
          }
        } else {
          // 默认值
          formData.value.loan_type = props.defaultLoanType || list.loanTypeList.filter((v) => v?.value == "INCOME")[0]?.value || undefined;
        }
        if (formData.value.amount) {
          isdisabled.value = true;
        }
        if (props.defaultAmount) {
          formData.value.amount = props.defaultAmount;
        }
        if (bindExtraInfo?.cost_type) {
          formData.value.single_type = bindExtraInfo.cost_type;
          state.isDisabledSingleType = true;
        } else {
          formData.value.single_type = "";
          state.isDisabledSingleType = false;
        }

        getSetting();
        //   //流水账户
        //   let params = {buildIds: buildIds || undefined};
        //   if (state.billId) {
        //     params.billId = state.billId;
        //   }
        //   request.get("/org", "/bill/getAccountList", params).then((res) => {
        //     list.accountList = res.list.map((item) => ({
        //       value: item.id,
        //       label: item.name,
        //     }));
        //     if (list.accountList.length) {
        //       formData.value.account_id = list.accountList[0].value;
        //     }
        //   });
        
        // 判断租客id
        if(microAppData.record?.currentOwnerId){
          formData.value.owner_id = microAppData.record.currentOwnerId
        }
      });
      getCompanyList();
    };

    init();

    const toGetAccount = (company_id) => {
      state.companyList.forEach(item => {
        if (item.value == company_id) {
          getAccount([item])
        }
      })
    }

    const addAccount = () => {
      state.addVisible = true;
    }

    const addSuccess = () => {
      addAccountClose();
      if (formData.value.account_id) {
        toGetAccount(formData.value.account_id[0])
      }
    };

    const addAccountClose = () => {
      state.addVisible = false;
    };

    return {
      ...toRefs(state),
      dateFormatStr,
      formData,
      validateInfos,
      list,
      loading,
      isDisSpecial,
      getObjectId,
      goBack,
      submit,
      isdisabled,
      handleAmountChange,
      handleCompanyChange,
      cancel,
      addInvoice,
      successChange,
      getSetting,
      goSetting,
      addAccount,
      addSuccess,
      addAccountClose,
      getAccount,
      microAppData,
      isDrawer

    };
  },
});
</script>

<style lang="less" scoped>

.new-turnover {
  height: 100%;
  display: flex;
  flex-direction: column;

  .header {
    height: 50px;
    background: #fff;

    color: rgba(0, 0, 0, 0.85);
    font-weight: 600;

    .ttile {
      margin-right: 12px;
      font-size: 20px;
    }

    .subtitle {
      margin-left: 12px;
      font-size: 15px;
    }

    &:deep(.ant-page-header) {
      padding: 10px 20px;
    }
  }

  &.back-class {
    :deep(.ant-page-header-back) {
      display: none;
    }
  }

  .content {
    flex: 1;
    padding: 10px;
    margin: 10px;
    max-height: calc(~"100%- 160px");
    overflow-y: auto;

    .building {
      height: 500px;
    }
  }

  .footer {
    height: 50px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 20px;
    box-sizing: border-box;
    background: #f7f7f7;
  }

  .hide-back {
    :deep(.ant-page-header-back) {
      display: none;
    }
  }
}


.fast-add {
  font-size: 12px;
  position: absolute;
  padding-right: 0;
  padding-left: 12px;
  top: -33px;
  right: -5px;
}

.ant-card-grid {
  width: 100%;
}
</style>
